package com.codeyang.listener;

import com.alibaba.fastjson.JSON;
import com.codeyang.config.WxMsgAutoConfiguration;
import com.codeyang.config.WxMsgProperties;
import com.codeyang.constant.QueueConstant;
import com.codeyang.model.WxMsgModel;
import com.codeyang.service.SmsLogService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * 描述: 微信消息发送监听MQ 发送消息
 *
 * @author CodeYang_Site
 * @version 2021/5/30 23:49
 */
@Slf4j
@Component
public class WsMsgListener {

    @Autowired
    private WxMsgAutoConfiguration wxMsgAutoConfiguration;

    @Autowired
    private WxMsgProperties wxMsgProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsLogService smsLogService;



    @RabbitListener(queues = QueueConstant.WECHAT_MSG_QUEUE, concurrency = "3-5")
    public void handlerWxMSg(Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.info("有微信消息进来了");
        String msg = new String(message.getBody());
        WxMsgModel wxMsgModel = JSON.parseObject(msg, WxMsgModel.class);
        try {
            // 发消息之前先从redis获取wx的token  如果拿不到  你获取 一次 设置进去
            //这里可以看一下这个消息
            ResponseEntity<String> result = realSendWxMsg(wxMsgModel);
            // 记录数据库
            smsLogService.saveWxMsg(wxMsgModel, result);
            channel.basicAck(deliveryTag, false);
            log.info("发送微信消息成功");
        } catch (Exception e) {
            log.info("发送微信消息失败");
        }

    }

    /**
     * 真正的发送微信消息服务
     * 就是向 微信的一个URL 发POST请求
     * @param wxMsgModel
     * @return
     */
    private ResponseEntity<String> realSendWxMsg(WxMsgModel wxMsgModel) {
        String msgUrl = wxMsgProperties.getMsgUrl();
        //组装了 access_token
        String sendMsgUrl = String.format(msgUrl, wxMsgAutoConfiguration.getWxAccessToken());
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(sendMsgUrl, wxMsgModel, String.class);

        System.out.println(responseEntity.getStatusCode());
        System.out.println(responseEntity.getBody());

        return responseEntity;
    }

}
